package com.base.api.sys.impl;

import com.alibaba.fastjson.JSONObject;
import com.base.api.sys.SysCacheService;
import com.base.vo.sys.CacheInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysCacheServiceImpl implements SysCacheService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取所有的缓存
     *
     * @return
     */
    @Override
    public String getAllKey() {
        Map<String, Object> map = new HashMap<>();
        Set<String> keys = stringRedisTemplate.keys("*");
        List<CacheInfo> list = new ArrayList<>();
        for (String keyName : keys) {
            CacheInfo cacheInfo = new CacheInfo();
            cacheInfo.setKeyName(keyName);
            cacheInfo.setKeyType(stringRedisTemplate.type(keyName).name().toLowerCase());
//            cacheInfo.setKeyValue(JSONObject.toJSONString(stringRedisTemplate.opsForValue().get(keyName)));
            cacheInfo.setActiveTime(stringRedisTemplate.getExpire(keyName));
            list.add(cacheInfo);
        }
        map.put("code", "0");
        map.put("data", list);
        return JSONObject.toJSONString(map);
    }

    /**
     * 根据键名删除指定缓存
     *
     * @param keyName
     * @return
     */
    @Override
    public String delKeyByName(String keyName) {
        return null;
    }

    /**
     * 获取值
     *
     * @param keyName
     * @return
     */
    @Override
    public String getCacheByKeyName(String keyName) {
        if (keyName != null && StringUtils.isNotBlank(keyName)) {
            switch (stringRedisTemplate.type(keyName)) {
                case STRING:
                    return stringRedisTemplate.opsForValue().get(keyName);
                case HASH:
                    return Arrays.toString(stringRedisTemplate.opsForHash().values(keyName).toArray());
            }
        }
        return null;
    }

    @Override
    public String delCacheByKeyName(String keyName) {
        Map<String, Object> map = new HashMap<>();
        if (keyName != null && StringUtils.isNotBlank(keyName)) {
            map.put("code", "0");
            map.put("data", stringRedisTemplate.delete(keyName));
        } else {
            map.put("code", "400");
            map.put("data", "keyName不能为空！");
        }
        return JSONObject.toJSONString(map);
    }
}
